
import tensorflow as tf
class TCNNConfig(object):
    embedding_dim = 64 #词向量维度
    seq_leng = 600
    num_classes =10
    num_fiters =256
    kernel_size = 5
    vocab_size = 5000
    hidden_dim = 128

    droup_keep_prob = 0.5
    learning_rate = 1e-3

    batch_size = 64
    num_epochs = 10

    print_per_batch = 100
    save_per_batch = 10

class TextCNN(object):
    def __init__(self,config):
        self.config = config

        #三个待输入的数据
        self.input_x=tf.placeholder(tf.int32,[None,self.config.seq_length],name='input')
        self.input_y=tf.placeholder(tf.float32,[None,self.config.num_classes],name='input_y')
        self.keep_prob= tf.placeholder(tf.float32,name='keep_prob')

        self.cnn()
    def cnn(self):
        #词向量映射
        with  tf.device('/cpu:0'):
            embedding = tf.get_variable('embedding',[self.config.vocab_size,self.config.embeddng_dim])
            embedding_inputs = tf.nn.embedding_lookup(embedding,self.input_x)
        with tf.name_scope("cnn"):
            #CNN layer
            conv = tf.layers.conv1d(embedding_inputs,self.config.num_filters,self.config.kernel_sze,
                                    name='conv')
            gmp = tf.reduce_max(conv,reduction_indices=[1],name='gmp')
        with tf.name_scope("score"):
            #全连接层，后面接dropout以及relu激活
            fc = tf.layers.dense(gmp,self.config.keep_prob)
            fc = tf.contrib.layers.dropout(fc,self.keep_prob)
            fc = tf.nn.relu(fc)
            #分类器
            self.logits = tf.layers.dense(fc,self.config.num_classes,name='fc2')
            self.y_pred_cls = tf.arg_max(tf.nn.softmax(self.logits),1)

        with tf.name_scope("optimize"):
            cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=self.logits,
                        labels=self.input_y)
            self.loss = tf.reduce_mean(cross_entropy)

            #优化器
            self.optim = tf.train.AdamOptimizer(learning_rate=self.config.learning_rate).minimize(self.loss)

        with tf.name_scope("ccuracy"):

            correct_pred  =tf.equal(tf.argmax(self.input_y,1),self.y_pred_cls)
            self.acc = tf.reduce_mean(tf.cast(correct_pred,tf.float32))